package com.janko.springbootbase.controller.delay;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * @Description 延时队列类-jdk实现
 * @Author nieyankang
 * @Version 1.0
 */
public class DelayOrder_JDK implements Delayed {

    /**
     * 优点:效率高,任务触发时间延迟低。
     * 缺点:(1)服务器重启后，数据全部消失，怕宕机
     *    (2)集群扩展相当麻烦
     *    (3)因为内存条件限制的原因，比如下单未付款的订单数太多，那么很容易就出现OOM异常
     *    (4)代码复杂度较高
     */

    private String orderId;
    private long timeout;

    public DelayOrder_JDK(String orderId, long timeout) {
        this.orderId = orderId;
        this.timeout = timeout;
    }

    // 返回距离你自定义的超时时间还有多少
    @Override
    public long getDelay(TimeUnit unit) {
        return unit.convert(timeout - System.nanoTime(), TimeUnit.NANOSECONDS);
    }

    @Override
    public int compareTo(Delayed other) {
        if (other == this)
            return 0;
        DelayOrder_JDK t = (DelayOrder_JDK) other;
        long d = (getDelay(TimeUnit.NANOSECONDS) - t.getDelay(TimeUnit.NANOSECONDS));
        return d == 0 ? 0 : (d < 0 ? -1 : 0);
    }

    void print() {
        System.out.println(orderId + "编号的订单要删除啦。。。。");
    }
}